using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using Nsb.Classes;
using jQueryApi;

// ReSharper disable UnusedMember.Global

namespace PlayNexus.Classes
{
    [IgnoreNamespace]
    public static class LineCounter
    {
        private static readonly bool Once = Initialize();
        private static jQueryObject _counter;
        private static int _count;
        private static int _height;
        private static int _timer;
        private static int _padding;
        public const string EventName = "TabLineCounter";

        private static bool Initialize()
        {
            jQuery.Document.Bind(EventName, CountEv);
            return !Once;
        }

        [AlternateSignature]
        public static extern void CountEv(jQueryEvent e);

        public static void CountEv(jQueryEvent e, jQueryObject el) // Could extend this to initialize other counter schemes
        {
            if (el == null || Type.GetScriptType(el) == "boolean")
            {
                Window.ClearInterval(_timer);
                if (_counter != null)
                    _counter.Remove();
                _counter = null;
                return;
            }

            if (_counter == null)
            {
                _count = _height = 0;
                _padding = 0 - Number.ParseInt(el.GetCSS("line-height"));
                const string style = "position: absolute; top: 0; left: 0; width: 30px; border: 1px dotted gold; background-color: rgba(0,0,0,.7); color: gold; text-align: center; font-size: 8pt;";
                _counter = jQuery.FromHtml("<div class='Mojo AboveHider'/>")
                    .AppendTo(Document.Body)
                    .Attribute("style", style)
                    ;
                _padding = 0 - ((Number.ParseInt(el.GetCSS("line-height")) - Number.ParseInt(_counter.GetCSS("line-height"))) / 2);
                CountTabLinesIn(el);
                //Window.SetTimeout(delegate { _counter.Plugin<Jewl>().Position(new Dictionary("my", "right bottom", "at", "left bottom", "of", el, "collision", "none none")); }, 1);
                _timer = Window.SetInterval(delegate { DomElement.Trigger(EventName, el); }, 500);
                return;
            }

            CountTabLinesIn(el);
        }

        private static void CountTabLinesIn(jQueryObject el)
        {
            string[] cnt = el.GetValue().Split("\n");
            int was = _count;
            _count = cnt.Length - 1;
            int h = el.GetHeight();
            if (was != _count || _height != h)
            {
                _height = h;
                _counter.Html(_count.ToString());
                Window.SetTimeout(delegate { _counter.Plugin<Jewl>().Position(new Dictionary("my", "right bottom", "at", "left bottom", "of", el, "collision", "none none", "offset", "0 " + _padding)); }, 1);
            }
        }
    }
}
